﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Sales
{
    public partial class frmMaintainCustomer : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public MstCustomerEntity selectedCustomer { get; set; }
        private MstPersonEntity mCustomerPerson;

        private List<MstCustomerContactEntity> DeleteList = new List<MstCustomerContactEntity>();
        private List<MstPersonCustomerEntity> DelSalesmans = new List<MstPersonCustomerEntity>();
        #endregion

        #region Constructor
        public frmMaintainCustomer()
        {
            InitializeComponent();
            if (selectedCustomer == null)
            {
                selectedCustomer = new MstCustomerEntity();
                selectedCustomer.CustomerId = Guid.NewGuid().ToString();
            }
        }
        #endregion

        #region Functions
        private void InitGridData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("PERSON_ID");
            dt.Columns.Add("CUSTOMER_ID");
            dt.Columns.Add("EFFIECTIVE_DATE", typeof(DateTime));
            dt.Columns.Add("NAME_CN");
            dt.Columns.Add("PERSON_CODE");
            gvSalesmans.DataSource = dt;
        }

        private void BingCombobox()
        {
            //UICommonFunctions.BindComboboxByCommonItem(cmbCustomerType, "CT", true);
            UICommonFunctions.BindComboboxByCommonItem(cmbCustomerLelve, "CL", true);
            UICommonFunctions.BindComboboxByCommonItem(cmbDefaultCurrency, "CS", true);
            UICommonFunctions.BindComboboxByCommonItem(cmbIsDelete, "STATUS", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colCONTACT_LEVEL, "CLEVEL", false);

            DataTable dt = MstIndustryTypeBs.GetAllIndustryType();
            DataRow dr = dt.NewRow();
            dr["INDUSTRY_TYPE_CODE"] = "";
            dt.Rows.InsertAt(dr, 0);
            cmbCustomerType.DataSource = dt;
            cmbCustomerType.DisplayMember = "INDUSTRY_TYPE_NAME";
            cmbCustomerType.ValueMember = "INDUSTRY_TYPE_CODE";
        }

        private void BindDataGridDetail()
        {
            string customerId = "";
            if (selectedCustomer != null)
            {
                customerId = selectedCustomer.CustomerId;
            }
            DataSet ds = MstCustomerContactBs.GetDataSetByCustomerId(customerId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvCustomerContect.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvCustomerContect.DataSource = dt;
            DeleteList = new List<MstCustomerContactEntity>();
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (selectedCustomer == null)
            {
                return;
            }
            txtCustomerCode.Text = selectedCustomer.CustomerCode;
            if (string.IsNullOrEmpty(txtCustomerCode.Text))
            {
                txtCustomerCode.Text = "自动生成";
            }
            txtCustomerName.Text = selectedCustomer.CustomerName;
            txtCustomerFullName.Text = selectedCustomer.CustomerFullName;
            cmbCustomerType.SetSelectedValue(selectedCustomer.IndustryTypeCode);
            cmbCustomerLelve.SetSelectedValue(selectedCustomer.Level);
            txtTelePhone.Text = selectedCustomer.Telephone;
            txtBank.Text = selectedCustomer.Bank;
            txtBankAccount.Text = selectedCustomer.BankAccount;
            txtTaxAccount.Text = selectedCustomer.TaxAccount;
            cmbIsDelete.SetSelectedValue(selectedCustomer.Status);
            cmbDefaultCurrency.SetSelectedValue(selectedCustomer.DefaultCurrency);
            //国家、省份、城市
            txtCountry.Text = selectedCustomer.Countory;
            txtProvince.Text = selectedCustomer.Province;
            txtCity.Text = selectedCustomer.City;
            txtZipCode.Text = selectedCustomer.ZipCode;
            txtAddress.Text = selectedCustomer.Address;
            txtEmail.Text = selectedCustomer.Email;
            txtReceivedPerson.Text = selectedCustomer.ReceivedPerson;
            txtReceivedAddress.Text = selectedCustomer.ReceivedAddress;
            txtFax.Text = selectedCustomer.Fax;
            txtLegalRepresentative.Text = selectedCustomer.LegalRepresentative;
            txtLegalAgent.Text = selectedCustomer.LegalAgent;

            DataTable dtSalesman = MstPersonCustomerBs.GetSalesmanForCustomer(selectedCustomer.CustomerId);
            dtSalesman.AcceptChanges();
            gvSalesmans.DataSource = dtSalesman;
        }

        private void SetEntity()
        {
            if (selectedCustomer == null)
            {
                selectedCustomer = new MstCustomerEntity();
                selectedCustomer.CustomerId = Guid.NewGuid().ToString();
            }
            selectedCustomer.CustomerCode = txtCustomerCode.Text;
            selectedCustomer.CustomerName = txtCustomerName.Text;
            selectedCustomer.CustomerFullName = txtCustomerFullName.Text;
            selectedCustomer.Telephone = txtTelePhone.Text;
            selectedCustomer.BankAccount = txtBankAccount.Text;
            selectedCustomer.TaxAccount = txtTaxAccount.Text;
            selectedCustomer.ZipCode = txtZipCode.Text;
            selectedCustomer.Address = txtAddress.Text;
            selectedCustomer.Email = txtEmail.Text;
            selectedCustomer.Countory = txtCountry.Text;
            selectedCustomer.Province = txtProvince.Text;
            selectedCustomer.City = txtCity.Text;
            selectedCustomer.LastModifiedDate = DateTime.Now;
            selectedCustomer.LastModifiedBy = CommonParameter.CurrentUser.PersonId;

            if (cmbCustomerType.SelectedValue != null && cmbCustomerType.SelectedValue.ToString().Trim() != "")
            {
                selectedCustomer.IndustryTypeCode = cmbCustomerType.SelectedValue.ToString();
            }
            if (cmbCustomerLelve.SelectedValue != null && cmbCustomerLelve.SelectedValue.ToString().Trim() != "")
            {
                selectedCustomer.Level = cmbCustomerLelve.SelectedValue.ToString();
            }
            selectedCustomer.Bank = txtBank.Text;
            if (cmbIsDelete.SelectedValue != null && cmbIsDelete.SelectedValue.ToString().Trim() != "")
            {
                //selectedCustomer.Status = CommonFunctions.ToInt32(cmbIsDelete.SelectedValue);
                selectedCustomer.Status = cmbIsDelete.SelectedValue.ToString();
            }
            if (cmbDefaultCurrency.SelectedValue != null && cmbDefaultCurrency.SelectedValue.ToString().Trim() != "")
            {
                selectedCustomer.DefaultCurrency = cmbDefaultCurrency.SelectedValue.ToString();
            }

            //selectedCustomer.ContactName = txtContacter.Text;
            //selectedCustomer.ContactMobilePhone = txtContoctPhone.Text;
            //selectedCustomer.ContactDepartment = txtContactDepartment.Text;
            //selectedCustomer.ContactAge = CommonFunctions.ToInt32(txtContactAge.Text);
            //selectedCustomer.ContactJobTitle = txtContactJobTitle.Text;
            //selectedCustomer.ContactOfficePhone = txtContactOfficePhone.Text;
            //selectedCustomer.ContactFax = txtContactFax.Text;
            //selectedCustomer.ContactEmail = txtContactEmail.Text;
            //selectedCustomer.ContactRemark = txtContactRemark.Text;

            selectedCustomer.ReceivedPerson = txtReceivedPerson.Text;
            selectedCustomer.ReceivedAddress = txtReceivedAddress.Text;
            selectedCustomer.Fax = txtFax.Text;

            selectedCustomer.LegalRepresentative = txtLegalRepresentative.Text;
            selectedCustomer.LegalAgent = txtLegalAgent.Text;

        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtCustomerCode.Text))
            {
                MessageBox.Show("客户编码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomerName.Text))
            {
                MessageBox.Show("客户简称不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomerFullName.Text))
            {
                MessageBox.Show("客户全称不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvCustomerContect.DataSource == null)
            {
                MessageBox.Show("联系人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvCustomerContect.DataSource as DataTable;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("联系人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbCustomerType.Text))
            {
                MessageBox.Show("请选择一种客户类型！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtProvince .Text ))
            {
                MessageBox.Show("客户省份不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCity .Text ))
            {
                MessageBox.Show("客户城市不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                //SetEntity();  //*

                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    selectedCustomer.Status = "STATUS01";//*
                    DataTable dtSalesman = (DataTable)gvSalesmans.DataSource;
                    DataTable dt = (DataTable)gvCustomerContect.DataSource;
                    bool isSuccessful = MstCustomerBs.SaveCustomer(true, selectedCustomer, dtSalesman, DelSalesmans, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    if (selectedCustomer.Status == "STATUS04")
                    {
                        selectedCustomer.Status = "STATUS01";
                    }
                    DataTable dtSalesman = (DataTable)gvSalesmans.DataSource;
                    DataTable dt = (DataTable)gvCustomerContect.DataSource;
                    bool isSuccessful = MstCustomerBs.SaveCustomer(false, selectedCustomer, dtSalesman, DelSalesmans, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.ApprovedModify)
                {
                    selectedCustomer.Status = "STATUS02";
                    DataTable dtSalesman = (DataTable)gvSalesmans.DataSource;
                    DataTable dt = (DataTable)gvCustomerContect.DataSource;
                    bool isSuccessful = MstCustomerBs.SaveCustomer(false, selectedCustomer, dtSalesman, DelSalesmans, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            if (ThisActionType == ActionType.New)
            {
                this.Text = "客户档案--新增";
            }
            else if (ThisActionType == ActionType.Modify)
            {
                this.Text = "客户档案--修改";
            }
            else if (ThisActionType == ActionType.Approve)
            {
                this.Text = "客户档案--审核";
            }
            else if (ThisActionType == ActionType.ApprovedModify)
            {
                this.Text = "客户档案--重新修改";
            }
            InitGridData();
            BingCombobox();
            SetFields();
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                selectedCustomer = new MstCustomerEntity();
                selectedCustomer.CustomerId = Guid.NewGuid().ToString();
                mCustomerPerson = null;
                ThisActionType = ActionType.New;
                txtCustomerCode.Properties.ReadOnly = false;
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (selectedCustomer != null)
            {
                try
                {
                    selectedCustomer.Status = "STATUS03";
                    bool successful = MstCustomerBs.UpdateMstCustomer(selectedCustomer);
                    if (successful)
                    {
                        MessageBox.Show("审核成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            else
            {
                MessageBox.Show("审核失败，请重新选择客户后再审核！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        protected override void Click_Reject()
        {
            if (selectedCustomer != null)
            {
                try
                {
                    selectedCustomer.Status = "STATUS04";
                    bool successful = MstCustomerBs.UpdateMstCustomer(selectedCustomer);
                    if (successful)
                    {
                        MessageBox.Show("拒审成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            else
            {
                MessageBox.Show("操作失败，请重新选择客户后再拒审！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private DataRow drContectSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drContectSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void txtProvince_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainAreaQuery frm = new frmMaintainAreaQuery(true, txtProvince.Text);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedArea != null)
            {
                txtProvince.Text = frm.SelectedArea.AreaName;
                txtProvince.Tag = frm.SelectedArea;
            }
            else
            {
                txtProvince.Text = "";
                txtProvince.Tag = null;
            }
        }

        private void txtCity_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainAreaQuery frm = new frmMaintainAreaQuery();
            if (txtProvince.Tag != null && txtProvince.Tag.GetType() == typeof(MstAreaEntity))
            {
                frm = new frmMaintainAreaQuery((MstAreaEntity)txtProvince.Tag);
            }
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedArea != null)
            {
                txtCity.Text = frm.SelectedArea.AreaName;
                txtCity.Tag = frm.SelectedArea;
            }
            else
            {
                txtCity.Text = "";
                txtCity.Tag = null;
            }
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (gvCustomerContect.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvCustomerContect.DataSource;
            DataRow dr = dt.NewRow();
            dr["CONTACT_ID"] = Guid.NewGuid().ToString();
            dr["CONTACT_LEVEL"] = "CLEVEL01";
            dr["CUSTOMER_ID"] = selectedCustomer.CustomerId;
            dr["LAST_MODIFIED_DATE"] = DateTime.Now;
            dr["LAST_MODIFIED_BY"] = CommonParameter.CurrentUser.PersonId;
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (gvCustomerContect.DataSource == null)
            {
                return;
            }
            if (drContectSelected == null)
            {
                return;
            }

            if (drContectSelected.RowState != DataRowState.Added)
            {
                MstCustomerContactEntity entity = new MstCustomerContactEntity(drContectSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvCustomerContect.DataSource as DataTable;
            dt.Rows.Remove(drContectSelected);

        }

        private DataRow drTemp;
        private void tsmNewSalesmen_Click(object sender, EventArgs e)
        {
            DataTable dt = gvSalesmans.DataSource as DataTable;
            drTemp = dt.NewRow();
            dt.Rows.Add(drTemp);
        }

        private void tsmDelSalesman_Click(object sender, EventArgs e)
        {
            if (gridView2.GetSelectedRows().Length == 0)
            {
                return;
            }
            DataTable dt = gvSalesmans.DataSource as DataTable;
            DataRow dr = dt.Rows[gridView2.GetSelectedRows()[0]];
            if (dr.RowState == DataRowState.Unchanged)
            {
                DelSalesmans.Add(new MstPersonCustomerEntity(dr));
                dt.Rows.Remove(dr);
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            frm.MultiSelected = true;
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPersonList != null)
            {
                DataTable dt = gvSalesmans.DataSource as DataTable;
                dt.Rows.Remove(drTemp);
                foreach (MstPersonEntity m in frm.SelectedPersonList)
                {
                    DataRow dr = dt.NewRow();
                    dr["PERSON_ID"] = m.PersonId;
                    dr["CUSTOMER_ID"] = selectedCustomer.CustomerId;
                    dr["NAME_CN"] = m.NameCn;
                    dr["PERSON_CODE"] = m.PersonCode;
                    MstPositionEntity position = MstPositionBs.GetMstPositionByID(m.PositionId);
                    if (position != null)
                    {
                        dr["POSITION_NAME"] = position.PositionName;
                    }
                    dt.Rows.Add(dr);
                }
                drTemp = null;
            }
        }
        #endregion
    }
}
